import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { CommonService } from 'src/app/service/common/common.service';
import { UsageCodeData, UserBindService } from 'src/app/service/user-bind.service';

@Component({
  selector: 'app-usage-code',
  templateUrl: './usage-code.component.html',
  styleUrls: ['./usage-code.component.scss']
})
export class UsageCodeComponent implements OnInit, OnChanges {
  @Input() isSingleRow = false

  @Input() type = '' // 用户编号类型

  @Input() field: any = null
  @Input() usageCode = ''
  @Input() usageCodeDisabled = false
  @Output() usageCodeChange = new EventEmitter()

  address = ''
  addressDisabled = true
  bindType = ''
  errorMsg = ''

  constructor(
    private userBind: UserBindService,
    private route: ActivatedRoute,
    private common: CommonService
  ) { }

  ngOnInit() {
    console.log(this.isSingleRow)
    this.getUsgaeCodeList()
  }
  ngOnChanges(changes: SimpleChanges): void {
    // console.log(222)
    // console.log(changes)
    // console.log(this.usageCode)
  }

  usageCodeList: UsageCodeData[] = []
  usageCodeLoading = false
  getUsgaeCodeList(){
    this.usageCodeLoading = true
    this.userBind._getBindList().subscribe({
      next: res => {
        this.usageCodeList = res
        this.usageCodeLoading = false
        let temp: UsageCodeData | undefined = this.usageCodeList.find((_: any) => _.usageCode === this.usageCode)
        if(this.usageCode && temp){
          this.address = temp.address
          this.bindType = temp.type
          this.usageCodeDisabled = true
  
          this.onUsageCodeChange(this.usageCode)
        }
      }, 
      error: error => {
        this.usageCodeLoading = false
      }
    })
  }

  onUsageCodeChange(usageCode: string){
    let temp: any = this.usageCodeList.find((_: any) => _.usageCode === usageCode)
    
    if(temp){
      this.address = temp.address
      
      let userNoStr = ''
      Object.entries(temp).forEach(([key, value]) => {
        if(value){
          userNoStr += `\"${key}\": \"${value}\",`
        }
      })
      if(userNoStr){
        userNoStr = `{${userNoStr.substring(0, userNoStr.length-1)}}`
      }
      
      let params = {
        usageCode: temp.usageCode,
        address: temp.address,
        bindType: temp.bindType,
        userNo: userNoStr
      }
      this.usageCodeChange.emit(params)
    }
  }

  userType = {
    masterHelp: {
      type: 'owner',
      meter: 'hide'
    },
    masterMeterHelp: {
      type: 'owner',
      meter: ''
    },
    userHelp: {
      type: '',
      meter: 'hide'
    },
    userMeterHelp: {
      //显示全部用户
      type: '',
      //显示表码
      meter:  ''
    }
  }

}
